﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Configuration;
using BaseData;
using BaseData.Exts;
using BaseData.Models;
using BaseLib.Helper;
using BaseUtility;
namespace WebUI.Ashx.Acc.Staff
{
    /// <summary>
    /// NewsAdminInfoForm 的摘要说明
    /// </summary>
    public class NewsAdminInfoForm : Base, IHttpHandler
    {
        private static readonly AccClass _accId = new AccExts(new GetAccType().Parse(Request.QueryString["url"])).Instances;
        public void ProcessRequest(HttpContext context)
        {
            if (_accId.Id == 0 || string.IsNullOrWhiteSpace(_accId.Name) || _accId.Type == 0) return;
            Response.Write(Msg(context).ObjectsToJson());
            Response.ContentType = "text/plain";
        }
        private static MsgErr Msg(HttpContext context)
        {
            var action = (Enums.Action)Enum.Parse(typeof(Enums.Action), Request.QueryString["action"]);
            var actstr = string.Empty;
            switch (action)
            {
                case Enums.Action.ActNew: actstr = "新建"; break;
                case Enums.Action.ActEdit: actstr = "修改"; break;
                case Enums.Action.ActStop: actstr = "停止"; break;
                case Enums.Action.ActView: actstr = "查看"; break;
                case Enums.Action.ActDelete: actstr = "删除"; break;
                default: return new MsgErr { error = 1, action = actstr, message = new StringBuilder("未知的操作方式！"), };
            }
            if (!Request.HttpMethod.Compare("POST", true)) return new MsgErr { error = 1, action = actstr, message = new StringBuilder("不支持Get方式！"), };
            var errflag = 0;
            var txtTitle = Request.Form["Title"].ToNull(); if (txtTitle.IsNullOrWhiteSpace()) errflag++;
            if (errflag != 0) return new MsgErr { error = 1, action = actstr, message = new StringBuilder("必要的输入项为空：【标题】！"), };
            var txtContent = (Request.Form["Content"] + "").Replace("<", "&lt;").Replace(">", "&gt;").ToNull();
            var id = Request.QueryString["id"].ToInt(0);
            var infoInit = new Web_Base_News_Info();
            var tempInfo = new Web_Base_News_Info();
            var infoExts = new Web_Base_News_Info_Ext();
            var tempExts = new Web_Base_News_Info_Ext();
            var resxInit = new Web_Base_Exts_Resx();
            var tempResx = new Web_Base_Exts_Resx();
            try
            {
                using (var ctx = new ContextExt())
                {
                    var nodeId = Request.QueryString["nodeId"].ToInt(0);
                    var nodes = ctx.Web_Base_News_Node.Where(q => q.PkId == nodeId);
                    var nodesExts = ctx.Web_Base_News_Node_Ext.Where(w => nodes.Select(s => s.NodeId).Contains(w.NodeId)).FirstOrDefault();
                    if (nodeId == 0 || !(nodes != null && nodes.FirstOrDefault() != null && nodes.Any())) return new MsgErr { error = 1, action = actstr, message = new StringBuilder("无父级节点ID！"), };
                    var node = nodes.FirstOrDefault();
                    #region 图片系列参数取得开始
                    var extTable = new Hashtable
		            {
		                {"image", "gif,jpg,jpeg,png,bmp"},
		                {"flash", "swf,flv,f4v,fla"},
		                {"media", "mp3,mp4,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"},
		                {"file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"}
		            };
                    var mcs = new Regex(@"src\s*=\s*['""]?([^'""\s]*)", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase).Matches(txtContent + "");
                    int imagesCount = 0, mediasCount = 0;
                    List<string> imagesList = new List<string>(), mediasList = new List<string>();
                    foreach (Match mc in mcs)
                    {
                        var src = mc.Groups[1].Value;
                        if (src.EndWith(".jpg") || src.EndWith(".jpeg") || src.EndWith(".png") || src.EndWith(".gif") || src.EndWith(".bmp"))
                        {
                            if (imagesCount == 0)
                            {
                                // tempInit.Image = src;
                                imagesCount++;
                            }
                            if (imagesList.Any(s => s == src)) continue;
                            imagesList.Add(src);
                        }
                        if (!src.EndWith(".flv") && !src.EndWith(".f4v") && !src.EndWith(".mp3") && !src.EndWith(".mp4") &&
                            !src.EndWith(".avi") && !src.EndWith(".mid") && !src.EndWith(".wav") && !src.EndWith(".mpg") &&
                            !src.EndWith(".wmv") && !src.EndWith(".wma") && !src.EndWith(".asf") && !src.EndWith(".rm") &&
                            !src.EndWith(".rma") && !src.EndWith(".ra") && !src.EndWith(".rmvb")) continue;
                        if (mediasCount == 0)
                        {
                            // tempInit.Media = src;
                            mediasCount++;
                        }
                        if (mediasList.Any(s => s == src)) continue;
                        mediasList.Add(src);
                    }
                    #endregion

                    {
                        tempInfo.AccType = (int)_accId.Type;
                        tempInfo.AccId = _accId.Id;
                        tempInfo.SortId = 0;
                        tempInfo.NodeId = nodeId;
                        tempInfo.Title = txtTitle;
                        tempInfo.TitleEn = Request.Form["TitleEn"].ToNull();
                        tempInfo.TitleSe = Request.Form["TitleSe"].ToNull();
                        tempInfo.TitleShort = Request.Form["TitleShort"].ToNull();

                        tempInfo.Content = txtContent;
                        tempInfo.Summary = Request.Form["Summary"].ToNull();

                        tempInfo.Tag = Request.Form["Tag"].ToNull();
                        tempInfo.KeyWord = Request.Form["KeyWord"].ToNull();

                        tempInfo.CssName = Request.Form["CssName"].ToNull();
                        tempInfo.CssNames = Request.Form["CssNames"].ToNull();

                        tempInfo.Folder = Request.Form["Folder"].ToNull();
                        tempInfo.Url = Request.Form["Url"].ToNull();
                        tempInfo.UrlEnable = Request.Form["UrlEnable"].ToInt();
                        tempInfo.Href = Request.Form["Href"].ToNull();

                        // tempInit.CreateIP = Request.ServerVariables["remote_addr"];
                        // tempInit.DateTimeCreate = System.DateTime.Now;

                        tempInfo.FlagPass = Request.Form["FlagPass"].ToInt(0);
                        tempInfo.FlagStatus = Request.Form["FlagStatus"].ToInt(0);
                        tempInfo.FlagStop = Request.Form["FlagStop"].ToInt(0);
                        tempInfo.FlagView = Request.Form["FlagView"].ToInt(0);

                        resxInit.Banner = Request.Form["Banner"].ToNull();
                        resxInit.Guide = Request.Form["Guide"].ToNull();
                        resxInit.Icon = Request.Form["Icon"].ToNull();
                        resxInit.ImagesCount = imagesList.Count;
                        resxInit.Images = string.Join(";", imagesList).ToNull();
                        resxInit.MediaCount = mediasList.Count;
                        resxInit.Media = string.Join(";", mediasList).ToNull();

                        tempExts.ValueInt1 = !nodesExts.KeyInt1.IsNullOrWhiteSpace() ? Request.Form["ValueInt1"].ToInt() : null;
                        tempExts.ValueInt2 = !nodesExts.KeyInt2.IsNullOrWhiteSpace() ? Request.Form["ValueInt2"].ToInt() : null;
                        tempExts.ValueInt3 = !nodesExts.KeyInt3.IsNullOrWhiteSpace() ? Request.Form["ValueInt3"].ToInt() : null;
                        tempExts.ValueFloat1 = !nodesExts.KeyFloat1.IsNullOrWhiteSpace() ? Request.Form["ValueFloat1"].ToDouble() : null;
                        tempExts.ValueFloat2 = !nodesExts.KeyFloat2.IsNullOrWhiteSpace() ? Request.Form["ValueFloat2"].ToDouble() : null;
                        tempExts.ValueFloat3 = !nodesExts.KeyFloat3.IsNullOrWhiteSpace() ? Request.Form["ValueFloat3"].ToDouble() : null;
                        tempExts.ValueString1 = !nodesExts.KeyString1.IsNullOrWhiteSpace() ? Request.Form["ValueString1"].ToNull() : null;
                        tempExts.ValueString2 = !nodesExts.KeyString2.IsNullOrWhiteSpace() ? Request.Form["ValueString2"].ToNull() : null;
                        tempExts.ValueString3 = !nodesExts.KeyString3.IsNullOrWhiteSpace() ? Request.Form["ValueString3"].ToNull() : null;
                        tempExts.ValueString4 = !nodesExts.KeyString3.IsNullOrWhiteSpace() ? Request.Form["ValueString4"].ToNull() : null;
                        tempExts.ValueString5 = !nodesExts.KeyString3.IsNullOrWhiteSpace() ? Request.Form["ValueString5"].ToNull() : null;
                        tempExts.ValueString6 = !nodesExts.KeyString3.IsNullOrWhiteSpace() ? Request.Form["ValueString6"].ToNull() : null;
                        tempExts.ValueDateTime1 = !nodesExts.KeyDateTime1.IsNullOrWhiteSpace() ? Request.Form["ValueDateTime1"].ToDateTime() : null;
                        tempExts.ValueDateTime2 = !nodesExts.KeyDateTime2.IsNullOrWhiteSpace() ? Request.Form["ValueDateTime2"].ToDateTime() : null;
                        tempExts.ValueDateTime3 = !nodesExts.KeyDateTime3.IsNullOrWhiteSpace() ? Request.Form["ValueDateTime3"].ToDateTime() : null;
                    };
                    switch (action)
                    {
                        case Enums.Action.ActView:
                        case Enums.Action.ActEdit:
                        case Enums.Action.ActNew:
                            switch (action)
                            {
                                case Enums.Action.ActNew:
                                    infoInit = new Web_Base_News_Info()
                                    {
                                        AccType = tempInfo.AccType,
                                        AccId = tempInfo.AccId,
                                        SortId = tempInfo.SortId,
                                        NodeId = tempInfo.NodeId,
                                        Title = tempInfo.Title,
                                        TitleSe = tempInfo.TitleSe,
                                        TitleEn = tempInfo.TitleEn,
                                        Content = tempInfo.Content,
                                        Summary = tempInfo.Summary,
                                        CssNames = tempInfo.CssNames,
                                        CssName = tempInfo.CssName,
                                        Tag = tempInfo.Tag,
                                        KeyWord = tempInfo.KeyWord,
                                        Url = tempInfo.Url,
                                        UrlEnable = tempInfo.UrlEnable,
                                        // CreateIP = tempInit.CreateIP,
                                        // DateTimeCreate = tempInit.DateTimeCreate,
                                        // FlagFocus = tempInit.FlagFocus,
                                        // flagHot = tempInit.flagHot,
                                        FlagPass = tempInfo.FlagPass,
                                        FlagStatus = tempInfo.FlagStatus,
                                        FlagStop = tempInfo.FlagStop,
                                        // Banner = tempInit.Banner,
                                        // Guide = tempInit.Guide,
                                        // Icon = tempInit.Icon,
                                        // ImagesCount = tempInit.ImagesCount,
                                        // Images = tempInit.Images,
                                        // Image = tempInit.Image,
                                        // MediaCount = tempInit.MediaCount,
                                        // Medias = tempInit.Medias,
                                        // Media = tempInit.Media,
                                        // ValueInt1 = tempInit.ValueInt1,
                                        // ValueInt2 = tempInit.ValueInt2,
                                        // ValueInt3 = tempInit.ValueInt3,
                                        // ValueFloat1 = tempInit.ValueFloat1,
                                        // ValueFloat2 = tempInit.ValueFloat2,
                                        // ValueFloat3 = tempInit.ValueFloat3,
                                        // ValueString1 = tempInit.ValueString1,
                                        // ValueString2 = tempInit.ValueString2,
                                        // ValueString3 = tempInit.ValueString3,
                                        // ValueDateTime1 = tempInit.ValueDateTime1,
                                        // ValueDateTime2 = tempInit.ValueDateTime2,
                                        // ValueDateTime3 = tempInit.ValueDateTime3,
                                    };
                                    break;
                                case Enums.Action.ActView:
                                case Enums.Action.ActEdit:
                                    var temps = ctx.Web_Base_News_Info.Where(q => q.NodeId == nodeId && q.PkId == id);
                                    if (!temps.Any()) return new MsgErr { error = 1, action = actstr, message = new StringBuilder("未找到要修改的记录！"), };
                                    infoInit = temps.FirstOrDefault();
                                    if (infoInit != null)
                                    {
                                        infoInit.AccType = tempInfo.AccType;
                                        infoInit.AccId = tempInfo.AccId;
                                        infoInit.Title = tempInfo.Title;
                                        infoInit.TitleSe = tempInfo.TitleSe;
                                        infoInit.TitleEn = tempInfo.TitleEn;
                                        infoInit.Content = tempInfo.Content;
                                        infoInit.Summary = tempInfo.Summary;
                                        infoInit.CssNames = tempInfo.CssNames;
                                        infoInit.CssName = tempInfo.CssName;
                                        infoInit.Tag = tempInfo.Tag;
                                        infoInit.KeyWord = tempInfo.KeyWord;
                                        infoInit.Url = tempInfo.Url;
                                        infoInit.UrlEnable = tempInfo.UrlEnable;
                                        infoInit.DateTimeUpdate = tempInfo.DateTimeUpdate;
                                        infoInit.FlagPass = tempInfo.FlagPass;
                                        infoInit.FlagStatus = tempInfo.FlagStatus;
                                        infoInit.FlagStop = tempInfo.FlagStop;
                                        resxInit.Banner = tempResx.Banner;
                                        resxInit.Guide = tempResx.Guide;
                                        resxInit.Icon = tempResx.Icon;
                                        resxInit.ImagesCount = tempResx.ImagesCount;
                                        resxInit.Images = tempResx.Images;
                                        resxInit.Image = tempResx.Image;
                                        resxInit.MediaCount = tempResx.MediaCount;
                                        resxInit.Media = tempResx.Media;
                                        infoExts.ValueInt1 = tempExts.ValueInt1;
                                        infoExts.ValueInt2 = tempExts.ValueInt2;
                                        infoExts.ValueInt3 = tempExts.ValueInt3;
                                        infoExts.ValueFloat1 = tempExts.ValueFloat1;
                                        infoExts.ValueFloat2 = tempExts.ValueFloat2;
                                        infoExts.ValueFloat3 = tempExts.ValueFloat3;
                                        infoExts.ValueString1 = tempExts.ValueString1;
                                        infoExts.ValueString2 = tempExts.ValueString2;
                                        infoExts.ValueString3 = tempExts.ValueString3;
                                        infoExts.ValueDateTime1 = tempExts.ValueDateTime1;
                                        infoExts.ValueDateTime2 = tempExts.ValueDateTime2;
                                        infoExts.ValueDateTime3 = tempExts.ValueDateTime3;
                                    }
                                    break;
                            }
                            ctx.Web_Base_News_Info.AddOrUpdate(m => m.PkId, infoInit);
                            ctx.SaveChanges();
                            return new MsgErr { error = 0, action = actstr, message = new StringBuilder("操作成功！"), };
                        default:
                            return new MsgErr { error = 0, action = actstr, message = new StringBuilder("未知操作！"), };
                    }
                }
            }
            catch (Exception err)
            {
                return new MsgErr { error = 1, action = actstr, message = new StringBuilder(value: "infoInit.PkId：" + infoInit.PkId + "\n" + err.Message), };
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}